package com.yuanli.cosmeticmirror.view.activity;

import android.Manifest;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.Toast;

import com.comenjoysoft.baselibrary.util.DeviceUtils;
import com.comenjoysoft.baselibrary.util.FileIOUtils;
import com.rxjava.rxlife.RxLife;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yuanli.cosmeticmirror.R;
import com.yuanli.cosmeticmirror.base.BaseActivity;
import com.yuanli.cosmeticmirror.base.Config;
import com.yuanli.cosmeticmirror.base.Constant;
import com.yuanli.cosmeticmirror.base.MyApp;
import com.yuanli.cosmeticmirror.bean.RingBean;
import com.yuanli.cosmeticmirror.utils.CommonUtils;
import com.yuanli.cosmeticmirror.utils.FileUtils;
import com.yuanli.cosmeticmirror.utils.MusicUtil;
import com.yuanli.cosmeticmirror.utils.RingUtils;
import com.yuanli.cosmeticmirror.utils.WebViewJsInject;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.Request;

public class MusicRingActivity extends BaseActivity {
    @BindView(R.id.music_back)
    ImageView musicBack;
    @BindView(R.id.web_view)
    WebView webView;
    private long mExitTime;
    private List<String> titleNameList = new ArrayList<>();
    private MusicUtil mMusicUtil = new MusicUtil(this);

    @Override
    protected int getContentView() {
        return R.layout.activity_music_ring;
    }

    @Override
    protected void init(Bundle bundle) {

    }

    @Override
    protected void initView() {
        initWebView();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void destroy() {
        clearWebViewResource();
    }


    @OnClick(R.id.music_back)
    public void onViewClicked() {
        if (titleNameList.size() > 1) {
            webView.loadUrl("javascript:KY.ine.goBack()"); // native调用js。返回上一页
            titleNameList.remove(titleNameList.size() - 1);
            //            mTvTitle.setText(titleNameList.get(titleNameList.size() - 1));
        } else {
            finish();
        }
    }

    private void initWebView() {
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); // 设置允许JS弹窗
        webSettings.setDomStorageEnabled(true); // 缓冲
        //   webSettings.setTextZoom(100);
        webSettings.setJavaScriptEnabled(true); // 让webView支持JS
        webView.loadUrl("https://iring.diyring.cc/friend/f614eceea9e646a8");
        //  mWebView.setInitialScale(100);


        // js调用native。
        // 1.声明需要注入到js的类;
        WebViewJsInject inject = new WebViewJsInject(handler);
        // 2. 调用WebView方法，注入客户端对象
        webView.addJavascriptInterface(inject, "KuYinExt");

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress > 70) {
                    // 网页加载完成
                    dialogDismiss();
                    //                    mProgressBar.setVisibility(View.GONE);//加载完网页进度条消失
                } else {
                    showLoadDialog();
                    // 加载中
                    //                    mProgressBar.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    //                    mProgressBar.setProgress(newProgress);//设置进度值
                }
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }
        });

        WebViewClient webViewClient = new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.i(TAG, "shouldOverrideUrlLoading: " + url);
                // 如下方案可在非微信内部WebView的H5页面中调出微信支付
                if (url.startsWith("weixin://wap/pay?")) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, android.net.http.SslError error) { // 重写此方法可以让webview处理https请求
                handler.proceed();
            }
        };
        webView.setWebViewClient(webViewClient);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constant.RING:
                    Bundle bundle = msg.getData();
                    RingBean ringBean = (RingBean) bundle.get("ringBean");
                    if (ringBean != null) {
                        setRing(ringBean);
                    }
                    break;
                case Constant.TITLE:
                    bundle = msg.getData();
                    ringBean = (RingBean) bundle.get("ringBean");
                    Log.i(TAG, "handleMessage: " + ringBean.toString());
                    //                    mTvTitle.setText(ringBean.getPname());
                    titleNameList.add(ringBean.getPname());
                    break;
                default:
                    break;

            }
        }
    };


    /**
     * 设置彩铃
     *
     * @param ringBean
     */
    private void setRing(RingBean ringBean) {

        checkAppPermission(ringBean);

    }

    private void checkAppPermission(RingBean ringBean) {
        new RxPermissions(this).request(
                Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribeOn(Schedulers.io())
                .as(RxLife.asOnMain(this))
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        try {
                            String fileName = ringBean.getWurl().substring(ringBean.getWurl().lastIndexOf("/") + 1);
                            String path = mMusicUtil.exists(ringBean.getWurl());
                            // 本地不存在该音频，则下载到本地
                            if (FileUtils.fileIsExists(path)) {
                                RingUtils.setRing(this, RingtoneManager.TYPE_RINGTONE, path, fileName);
                            } else {
                                downloadBgm(ringBean.getWurl(), ringBean.getWname());
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    } else {
                        showToast("请求权限失败");
                    }
                });
    }

    /**
     * 下载铃声
     *
     * @param musicUrl
     * @param musicName
     */
    private void downloadBgm(final String musicUrl, final String musicName) {
        if (DeviceUtils.getNetworkType(this) == 0) {
            showToast("网络异常");
            return;
        }
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(musicUrl)
                .get()
                .build();
        okhttp3.Call call = okHttpClient.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                showToast("网络异常,下载失败");
            }

            @Override
            public void onResponse(okhttp3.Call call, okhttp3.Response response) {
                if (response.body() != null) {
                    try {
                        // 得到服务器所传的文件内容
                        InputStream is = response.body().byteStream();
                        // 保存音频文件
                        String fileName = musicUrl.substring(musicUrl.lastIndexOf("/") + 1);
                        String localPath = FileUtils.getSDCardRoot()+Config.MUSIC_PATH+fileName;
                        FileIOUtils.writeFileFromIS(localPath,is);
                        RingUtils.setRing(MyApp.getInstance(), RingtoneManager.TYPE_RINGTONE, localPath, musicName);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    // 使用Webview的时候，返回键没有重写的时候会直接关闭程序，这时候其实我们要其执行的知识回退到上一步的操作
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 这是一个监听用的按键的方法，keyCode 监听用户的动作，如果是按了返回键，同时Webview要返回的话，WebView执行回退操作，因为mWebView.canGoBack()返回的是一个Boolean类型，所以我们把它返回为true
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();
            return true;
        } else if ((System.currentTimeMillis() - mExitTime) > 2 * 1000) {
            Toast.makeText(getApplicationContext(), "再按一次退出", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void clearWebViewResource() {
        if (webView != null) {

            webView.stopLoading();
            webView.removeAllViews();
            ((ViewGroup) webView.getParent()).removeView(webView);
            webView.setTag(null);
            webView.clearHistory();
            webView.destroy();
            webView = null;
        }
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }
}
